import _ from 'lodash';
import moment from 'moment';
import { serverUrl } from '../../../../config/urlConfig';
import type {
  IMarketOptions,
  IOriginCreatorOption,
  ICreatorOption,
  IOrginDealElementOptions,
  ICreatorOptionsObj,
  IOriginCreatorOptions,
  IGroupOptions,
  IGroupOptionsObj,
  IDateData,
} from './type';
import { downLoadFilePDF } from './service';

// 处理交易中心数据
export const dealMarketOptions = (data: IMarketOptions[]) => {
  const _data = data.map((item: any) => ({
    ...item,
    value: item?.code || '',
    label: item?.name || '',
  }));
  return _data;
};

// 处理交易单元数据
export const getDealElementOptions = (data: IOrginDealElementOptions[]) => {
  const _settlemen: Record<string, any> = {};
  let dataObj: Record<string, any> = {};
  const modalData: any[] = data.map((m: IOrginDealElementOptions) => {
    const _children = m?.children?.map((item: IOrginDealElementOptions) => {
      const children = item?.children?.map((n) => ({
        ...n,
        title: n?.label,
        key: n?.value,
        parentKey: item?.id,
        regionId: m?.value || '',
      }));
      dataObj = { ...dataObj, ..._.groupBy(children, 'value') };
      _settlemen[item.id] = children;
      return { ...item, key: item?.id, title: item?.label || '', children, parentKey: m?.id };
    });
    return { ...m, title: m?.label || '', children: _children, key: m?.value || '' };
  });
  return { modalData, value: _.flatten(Object.values(_settlemen)), dataObj };
};

// 处理创建人数据
export const getCreatorResultData = (data: IOriginCreatorOptions) => {
  const { userList = [], groupList = [] } = data || {};
  const creatorOptions: ICreatorOption[] = [];
  const creatorOptionsObj: ICreatorOptionsObj = {};
  const groupOptions: IGroupOptions[] = [];
  const groupOptionsObj: IGroupOptionsObj = {};
  userList?.forEach((item: IOriginCreatorOption) => {
    const key = String(item.userId);
    const obj = {
      ...item,
      label: item.name,
      value: item.userId,
    };
    creatorOptions.push(obj);
    creatorOptionsObj[key] = obj;
  });
  groupList.forEach((item: IGroupOptions) => {
    const key = String(item.groupId);
    const obj = {
      ...item,
      label: item.groupName,
      value: item.groupId,
      userList: item.userList?.map((i) => ({ ...i, label: i.name, value: i.userId })),
    };
    groupOptions.push(obj);
    groupOptionsObj[key] = obj;
  });
  return {
    creatorOptions,
    creatorOptionsObj,
    groupOptions,
    groupOptionsObj,
  };
};

// 初始日历数据
export const initValue = (value: any) => {
  return Number(moment(value).format('DD'));
};

// 生成数组
export const repeatMonth = () => {
  const arr = Array.from({ length: 31 }, (v, i) => ({
    label: String(i + 1),
    value: i + 1,
  }));
  return arr;
};

export const splitArrayByIntersection = (a = [], b = []) => {
  // 判断是否有交集
  const hasIntersection = a.some((item) => b.includes(item));

  // 拆分数组
  const intersection = [];
  const nonIntersection = [];

  a.forEach((item) => {
    if (b.includes(item)) {
      intersection.push(item);
    } else {
      nonIntersection.push(item);
    }
  });

  return {
    hasIntersection, // 布尔值，表示是否有交集
    intersection, // a数组中与b的交集部分
    nonIntersection, // a数组中不在b中的部分
  };
};

// 上传文件
export const uploadFn = async (system: boolean, obj: any) => {
  if (system) {
    const client = new OSS({
      region: 'oss-cn-beijing',
      accessKeyId: 'LTAI4G7w6tvFNPQ4q2hcHcD6',
      accessKeySecret: 'ZgALLEnmeqjjcTxlJnDEKKfJ6R5GUy',
      bucket: 'tianrun',
    });
    const url = client.signatureUrl(obj.annexPath, {
      expires: 3600,
      response: {
        'content-disposition': 'attachment; filename="' + obj.annexPath + '"',
      },
    });
    window.open(url);
  } else {
    window.open(`${serverUrl}/annex/annex/downLoadFile/${obj.annexId}`);
  }
};
/*
// 下载文件
export const getFileUrl = (file: any = {}, isDownLoad = false) => {
  // isDownLoad 是否强制下载
  const signatureConf: any = {
    expires: 3600,
  };
  if (isDownLoad) {
    signatureConf.response = {
      'content-disposition': `attachment; filename="${file.annexName}"`,
    };
  }
  const url = new OSS({
    region: 'oss-cn-beijing',
    accessKeyId: 'LTAI4G7w6tvFNPQ4q2hcHcD6',
    accessKeySecret: 'ZgALLEnmeqjjcTxlJnDEKKfJ6R5GUy',
    bucket: 'tianrun',
  }).signatureUrl(file.annexPath, signatureConf);
  return Promise.resolve(url);
*/

// 预览PDF文件
export const getFileUrl = async (file: any = {}, isDownLoad = false) => {
  const data = await downLoadFilePDF(file.annexPath);
  if (data && !data.statusCode) {
    const bolb = new Blob([data], { type: 'application/pdf;chartset=UTF-8' });
    return Promise.resolve(URL.createObjectURL(bolb));
  }
};

// 对象数组去重
export const uniqueFunc = (arr: any, uniId: string) => {
  const res = new Map();
  return arr.filter((item: any) => !res.has(item[uniId]) && res.set(item[uniId], 1));
};

// 获取日期
export const getDate = (date: string) => {
  const _date = date || moment().format('YYYY-MM-DD');
  const nowDay = moment(_date).daysInMonth();
  const nowDayArr = Array.from({ length: nowDay }, (v, i) => ({
    value: moment(_date).startOf('month').add(i, 'days').format('YYYY-MM-DD'),
    day: moment(_date).startOf('month').add(i, 'days').day(),
    isShow: true,
  }));
  let firstDay = moment(_date).startOf('month').day(); //本月第一天是周几
  firstDay = firstDay == 0 ? 6 : firstDay - 1;
  const beforeDateArr = Array.from({ length: firstDay }, (v, i) => ({
    value: moment(_date)
      .subtract(1, 'month')
      .endOf('month')
      .subtract(firstDay - 1, 'days')
      .add(i, 'days')
      .format('YYYY-MM-DD'),
    isShow: false,
  }));
  let lastDay = 6 - moment(_date).endOf('month').day(); //本月最后一台天是周几
  lastDay = lastDay == 6 ? 0 : lastDay + 1;
  const lastDateArr = Array.from({ length: lastDay }, (v, i) => ({
    value: moment(_date).add(1, 'month').startOf('month').add(i, 'days').format('YYYY-MM-DD'),
    isShow: false,
  })); //后面本月需要补的
  const arr: string[] = nowDayArr.map((item) => {
    return item.value;
  });
  const data = nowDayArr.map((item: IDateData) => {
    return item.value;
  });
  return {
    monthData: [...beforeDateArr, ...nowDayArr, ...lastDateArr] || [],
    nowMonthData: arr || [],
    dateList: data || [],
  };
};

export const downFile = (fileUrl: string, fileName = '未命名') => {
  if (!fileUrl) return;
  const _a = document.createElement('a');
  _a.href = fileUrl;
  _a.download = fileName;
  document.body.appendChild(_a);
  const evt = document.createEvent('MouseEvents');
  evt.initEvent('click', false, false);
  _a.dispatchEvent(evt);
  document.body.removeChild(_a);
};
